package org.stvd.controller.workflow.leave;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.stvd.common.Consts;
import org.stvd.common.aspectj.lang.annotation.Log;
import org.stvd.common.aspectj.lang.enums.BusinessType;
import org.stvd.common.security.SecurityUserHolder;
import org.stvd.common.utils.InterfaceResult;
import org.stvd.common.utils.ServiceResult;
import org.stvd.common.workflow.enums.WorkflowApplyStatusEnum;
import org.stvd.common.workflow.enums.WorkflowTypeEnum;
import org.stvd.controller.workflow.ApplyBaseController;
import org.stvd.core.dto.QueryResult;
import org.stvd.core.util.StringUtil;
import org.stvd.entities.admin.Roles;
import org.stvd.entities.admin.Users;
import org.stvd.entities.workflow.WfIndex;
import org.stvd.entities.workflow.leave.BsLeaveInfo;
import org.stvd.service.admin.DepartmentService;
import org.stvd.service.admin.UsersService;
import org.stvd.service.common.CodeTableService;
import org.stvd.service.workflow.ProcessCoreService;
import org.stvd.service.workflow.WfIndexService;
import org.stvd.service.workflow.leave.BsLeaveInfoService;

/**
 * @Title BsLeaveApplyController
 * @Destribution:请假控制层
 * @author fenglong
 * @date 2021年1月18日
 */
@Controller
@RequestMapping(value = "/workflow/leave/apply")
public class BsLeaveApplyController extends ApplyBaseController<BsLeaveInfo> {

    @Autowired
    private BsLeaveInfoService leaveInfoService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private CodeTableService codeTableService;
    @Autowired
    private WfIndexService wfIndexService;
    @Autowired
    private ProcessCoreService processCoreService;
    
    private String tmpURL = "/workflow/leave/apply/";

    @Override
    protected String loadPageManageData(BsLeaveInfo bsLeaveInfo) {
        if (StringUtil.isEmpty(bsLeaveInfo.getCreateUser())) {
            bsLeaveInfo.setCreateUser(SecurityUserHolder.getCurrentUserId());
        }
        map.put("bsLeaveInfo", bsLeaveInfo);
        QueryResult<Map<String, Object>> queryResult = leaveInfoService.getQueryResult((pageNo - 1) * pageSize, pageSize,
                bsLeaveInfo.getDepName(), bsLeaveInfo.getEmpName(), bsLeaveInfo.getStartDate(),
                bsLeaveInfo.getEndDate(), SecurityUserHolder.getCurrentUserId());
        map.put("queryResult", queryResult);
        map.put("applyStatusMap", WorkflowApplyStatusEnum.applyStatusMap);
        return tmpURL + "LeaveManage.html";
    }
 
    @Override
    protected String loadPageAddData(BsLeaveInfo bsLeaveInfo) {
        setProcessDefinitionKey(WorkflowTypeEnum.LeaveProcess.getValue());
        bsLeaveInfo.setDepId(SecurityUserHolder.getCurrentMaxAuthDepId());
        bsLeaveInfo.setDepName(SecurityUserHolder.getCurrentMaxAuthDep().getDepName());
        bsLeaveInfo.setEmpId(SecurityUserHolder.getCurrentUserId());
        bsLeaveInfo.setEmpName(SecurityUserHolder.getCurrentUserInfo().getUname());
        map.put("depList", departmentService.findAllDepByGuid(Consts.GUID));
        map.put("bsLeaveInfo", bsLeaveInfo);
        try {
            map.put("leaveTypeList", codeTableService.findAll("dic_leave_type"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tmpURL + "LeaveAdd.html";
    }
 
    @Override
    protected ServiceResult<Map<String, Object>> processStarted(WfIndex wfIndex, BsLeaveInfo bsLeaveInfo,
            Map<String, Object> variables) {
        return leaveInfoService.insertLeaveInfo(bsLeaveInfo, wfIndex, variables);
    }
 
    @Override
    protected ServiceResult<Map<String, Object>> processDelete(String processInstanceId) {
        return leaveInfoService.deleteLeaveInfo(processInstanceId);
    }
 
    @Override
    protected String processDetail(String processInstanceId) {
        BsLeaveInfo bsLeaveInfo = leaveInfoService.findByProcessId(processInstanceId);
        if (bsLeaveInfo != null) {
            if (bsLeaveInfo.getLeaveCategory().equals("1")) {
                bsLeaveInfo.setLeaveCategory("按小时请");
            } else {
                bsLeaveInfo.setLeaveCategory("按天请");
            }
            try {
                for (int i = 0; i < codeTableService.findAll("dic_leave_type").size(); i++) {
                    if (bsLeaveInfo.getLeaveType()
                            .equals(codeTableService.findAll("dic_leave_type").get(i).getId())) {
                        bsLeaveInfo.setLeaveType(codeTableService.findAll("dic_leave_type").get(i).getName());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            map.put("bsLeaveInfo", bsLeaveInfo);
            map.put("applyStatusMap", WorkflowApplyStatusEnum.applyStatusMap);
        }
 
        return tmpURL + "LeaveDetail.html";
    }
 
    @GetMapping(value = "edit/{id}")
    public String onEditLoad(@PathVariable Long id, @ModelAttribute("bsLeaveInfo") BsLeaveInfo bsLeaveInfo) {
        bsLeaveInfo = leaveInfoService.findByPk(BsLeaveInfo.class, id);
        List<Users> userList = usersService.findUsers("", "", "", Consts.GUID);
        map.put("userList", userList);
        map.put("depList", departmentService.findAllDepByGuid(Consts.GUID));
        map.put("bsLeaveInfo", bsLeaveInfo);
        try {
            map.put("leaveTypeList", codeTableService.findAll("dic_leave_type"));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return tmpURL + "LeaveEdit.html";
    }
 
    @PostMapping(value = "edit")
    @ResponseBody
    @Log(title = "修改请假申请信息", businessType = BusinessType.INSERT)
    public InterfaceResult<Map<String, Object>> onEditAction(
            @Valid @ModelAttribute("bsOvertimeInfo") BsLeaveInfo bsLeaveInfo, BindingResult bindingResult) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String, Object>>();
        if (bindingResult.hasErrors()) {
            result.setError(bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        ServiceResult<Map<String, Object>> serviceResult = leaveInfoService.editBsLeaveInfo(bsLeaveInfo);
        if (!serviceResult.isSuccess()) {
            result.setError(serviceResult.getMessage());
        }
        return result;
    }
 
    @Override
    protected Map<String, Object> conditionAdd(Map<String, Object> variables, BsLeaveInfo bsLeaveInfo) {
        if (bsLeaveInfo != null && bsLeaveInfo.getLeaveDays() != null) {
            variables.put("a", bsLeaveInfo.getLeaveDays());
        }
        // 当前登录用户的
        String depId = SecurityUserHolder.getCurrentMaxAuthDepId();
        // 当前用户在该机构的用户角色
        List<Roles> userRoleList = SecurityUserHolder.getCurrentRoleInfo(Consts.GUID, depId);
        if (userRoleList != null && userRoleList.size() > 0) {
            List<String> depList = new ArrayList<String>();
            depList.add(depId);
            for (int i = 0; i < userRoleList.size(); i++) {
                Roles role = userRoleList.get(i);
                if ("ROLE_MANAGE".equals(role.getRoleCode())) {
                    variables.put("userRole", "ROLE_MANAGE");
                    break;
                } else if ("ROLE_DEP_LEADER".equals(role.getRoleCode())) {
                    variables.put("userRole", "ROLE_DEP_LEADER");
                    break;
                } else if ("ROLE_DEP_STAFF".equals(role.getRoleCode())) {
                    variables.put("userRole", "ROLE_DEP_STAFF");
                    break;
                }
            }
        }
        return variables;
    }
    
    /**
     * @Destribution 申请撤销
     * @param processInstanceId
     * @return
     */
    @Log(title = "请假申请撤销", businessType = BusinessType.UPDATE)
    @PostMapping(value = "revoke")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onWorkflowDelete(String processInstanceId) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String, Object>>();
        ServiceResult<Map<String, Object>> serviceResult = leaveInfoService.revoke(processInstanceId);
        if (serviceResult.isSuccess()) {
            wfIndexService.delete(processInstanceId);
            processCoreService.deleteProcessInstanceById(processInstanceId, "撤销");
            result.setMsg("撤销成功！");
        } else {
            result.setError("撤销失败！<br/>失败原因：" + serviceResult.getMessage());
        }
        return result;
    }

}
